import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../common/routers/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/values/index.dart';
import 'index.dart';

///
/// url 在 app 内部打开
/// 目前就 ios 和 Android ，pc 端还是打开浏览器
///
class InnerWebviewPage extends GetView<InnerWebviewController> {
  const InnerWebviewPage({Key? key}) : super(key: key);

  static Future<void> open(String url) async {
    Uri uri = Uri.parse(url);
    if (GetPlatform.isDesktop) {
      if (await canLaunchUrl(uri)) {
        final result = await launchUrl(
          uri,
          mode: LaunchMode.externalApplication,
          webViewConfiguration: WebViewConfiguration(headers: <String, String>{
            O2ApiManager.instance.tokenName:
                O2ApiManager.instance.o2User?.token ?? ''
          }),
        );
        if (!result) {
          OLogger.e('打开 url $url 失败！');
        }
      } else {
        Loading.showError('common_error_url'.trArgs([url]));
      }
    } else {
      await Get.toNamed(O2OARoutes.commonInnerWebview,
          arguments: {"uri": url}, preventDuplicates: false);
    }
  }

  // 主视图
  Widget _buildView() {
    return InAppWebView(
        key: controller.webViewKey,
        initialUrlRequest: URLRequest(url: WebUri(controller.state.openUri)),
         initialSettings: InAppWebViewSettings(
          useShouldOverrideUrlLoading: true,
          useOnDownloadStart: true,
          javaScriptCanOpenWindowsAutomatically: true,
          mediaPlaybackRequiresUserGesture: false,
          applicationNameForUserAgent: O2.webviewUserAgent,
        ),
        onWebViewCreated: (c) {
          controller.setupWebviewJsHandler(c);
        },
        shouldOverrideUrlLoading: (c, navigationAction) async {
          var uri = navigationAction.request.url!;
          OLogger.d("shouldOverrideUrlLoading uri: $uri");
          return NavigationActionPolicy.ALLOW;
        },
        onProgressChanged: (c, p) {
          controller.progressChanged(c, p);
        },
        // h5下载文件
        onDownloadStartRequest: (c, request) async {
          controller.webviewHelper.onFileDownloadStart(request);
        },
        onTitleChanged: ((c, title) {
          OLogger.d('修改网页标题： $title');
          final host = O2ApiManager.instance.getWebHost();
          if (title != null && title.isNotEmpty && !title.contains(host)) {
            controller.state.title = title;
          }
        }),
        onConsoleMessage: (c, consoleMessage) {
          OLogger.i("console: $consoleMessage");
        });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<InnerWebviewController>(
      builder: (_) {
        return  PopScope(
            canPop: false,
            onPopInvokedWithResult: (didPop, result) {
              OLogger.d('============>onPopInvokedWithResult $didPop');
              if (didPop) {
                return;
              }
              controller.tapBackBtn();
            },
            child: Scaffold(
              appBar: AppBar(
                automaticallyImplyLeading: false,
                title: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    IconButton(
                      icon: const Icon(Icons.arrow_back),
                      onPressed: () => {controller.tapBackBtn()},
                    ),
                    IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () => {controller.tapCloseBtn()},
                    ),
                    Expanded(
                        flex: 1, child: Obx(() => Text(controller.state.title)))
                  ],
                ),
                actions: [
                  Obx(() => Visibility(
                      visible: controller.state.openUri.isNotEmpty,
                      child: IconButton(
                        icon: const Icon(Icons.more_vert),
                        onPressed: controller.tapShowMenu,
                      )))
                ],
              ),
              body: SafeArea(
                  child: Obx(
                () => controller.state.openUri.isEmpty
                    ? const Center(child: CircularProgressIndicator())
                    : _buildView(),
              )),
            ));
      },
    );
  }
}
